package com.example.medicine.controller;



import com.example.medicine.Bean.yonghu;
import com.example.medicine.Mapper.SystemFunctionMapper;
import com.example.medicine.Mapper.SystemRoleFunctionMapper;
import com.example.medicine.Mapper.SystemRoleMapper;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.config.MyRealm;
import com.example.medicine.md5_guid.md5_guid;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Controller
public class LoginController {
    @Autowired
    private yonghuMapper yonghuMapper;
    @Autowired
    private SystemRoleMapper systemRoleMapper;
    @Autowired
    private SystemRoleFunctionMapper systemRoleFunctionMapper;
    @Autowired
    private SystemFunctionMapper systemFunctionMapper;
    /**
     * 展示登录界面
     * @return
     */
    @RequestMapping("/login")
    public String showLogin(){
        log.info("showLogin登录页面");
        return "pages/login";
    }
    @RequestMapping("/logout")
    public String logout() {
        log.info("logout退出登录");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出用户
        return "pages/login";
    }


    /**
     * 接收登录请求，进行判断
     * @param userId
     * @param pwd
     * @param model
     * @return
     */

    @PostMapping(value = "/loginIn")
    public String login(@RequestParam("userId") String userId, @RequestParam("password") String pwd, Model model,  HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        log.info("login登录");
        String roleName = yonghuMapper.getTypeByUserId(userId);
        // 根据角色从 SystemRoleFunctionService 获取对应的功能（权限）ID
        String roleId = systemRoleMapper.getIdByName(roleName);
        Set<String> functionIds = systemRoleFunctionMapper.getFunIdByRoleId(roleId);
        // 将功能（权限）ID转换成权限名字
        Set<String> permissions = functionIds.stream()
                .map(functionId -> systemFunctionMapper.getNameById(functionId))
                .collect(Collectors.toSet());

        yonghu user = yonghuMapper.getPasswordByUserid(userId);
        yonghu temp = yonghuMapper.getById(userId);
        String teamname;
        if(temp!=null) {
            teamname= temp.getTeamName();
        }
        else {
            teamname = "";
        }
        try {
            //获取主体对象
            subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(userId, pwd));
            log.info("用户:"+subject.getPrincipal().toString());
            session.setAttribute("sessionUser",user);
            model.addAttribute("teamname", teamname);
            model.addAttribute("userid", userId);
            model.addAttribute("userType", permissions);
            return "/home";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("message", 1);
            log.info("用户名错误!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("message", 1);
            log.info("密码错误!");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }

        return "pages/login";
    }




}
